var title = "UCKeFu-全渠道客服系统" ;
var tipagent = '' , tipagenttitle = '', tipagenticon = '' , imlastping = 0 , agentready = false , agentbusy = false ;
var socket  , newuser = [] , newmessage = [] , ring = [];
newuser['mp3'] = '/images/new.mp3'; 
newmessage['mp3'] = '/images/message.mp3';
ring['mp3'] = '/images/ring.mp3';

/**
 * 服务器超时检查
 */
var timer = setInterval(function(){
	if($('#agentstatus').hasClass('layui-form-onswitch')){
		if(imlastping == 0){
			imlastping = new Date().getTime() ;
			if(socket!=null && socket.connected == true){
				socket.emit("agentstatus");
				socket.emit("ping");
			}
		}else{
			//超时没响应 PONG事件，服务器端无回应，提示网络已经断开
			/**
			top.layer.tips('网络链接已中断，请您刷新浏览器重新登录。', '#agents_status', {
				  tips: [3, '#FF5722'],
				  time:5000
			});
			**/
			imlastping = 0 ;
		}
	}
},5000);

var webIMAgent = {
		init:function(){
			socket = io.connect(schema+'://'+hostname+':'+port+'/im/agent?orgi='+orgi+"&userid="+userid+"&session="+session+"&admin="+adminuser , options);
		    socket.on('connect',function() {
				console.log("连接初始化成功，时间："+new Date().toLocaleTimeString());
				//请求服务端记录 当前用户在线事件
		    }).on('disconnect',function() {
				console.log("连接已断开，时间："+new Date().toLocaleTimeString());       
				//请求服务端记录，当前用户离线
				webIMAgent.off();
				webIMAgent.init();
				if(agentready == true){
					$('#agentstatus').addClass("layui-form-onswitch");
					loadURL("/agent/ready.html") ;
					
					if(agentbusy == true){
						$('#agentstatus_busy').addClass("layui-form-onswitch-busy");
						$('#agentstatus_busy').removeClass("layui-form-onswitch-notbusy");
						loadURL("/agent/busy.html")
					}
				}else{
					$('#agentstatus').removeClass("layui-form-onswitch");
					$('#agentstatus_busy').removeClass("layui-form-onswitch-busy").hide();
				}
		    });
			
		    socket.on('chatevent', function(data) {
				console.log(data.messageType + " .....  message:"+data.message);          
		    }).on('agentstatus',function(){
		    	var delay = new Date().getTime() - imlastping ;
				if(delay > 500){
					console.log('网络延迟时间超过了'+ delay + '毫秒，当前时间：'+ new Date().toLocaleTimeString());
				}
				if(delay > 1000){
					top.layer.tips('网络延迟时间超过了'+ delay + '毫秒', '#agents_status', {
						  tips: [3, '#FF5722'],
						  time:5000
					});
				}
				imlastping = 0 ;
			}).on("workstatus" , function(data){
				if(data.workresult == "leave"){	//未就绪
					agentready = false ;
					agentbusy = false ;
					$('#agentstatus').removeClass("layui-form-onswitch");
					$('#agentstatus_busy').removeClass("layui-form-onswitch-busy").hide();
				}else if(data.workresult == "busy"){	//未就绪
					agentready = true ;
					agentbusy = true ;
					
					$('#agentstatus').addClass("layui-form-onswitch");
					$('#agentstatus_busy').addClass("layui-form-onswitch-busy").show();
				}else if(data.workresult == "ready" || data.workresult == "notbusy"){			//SUCCESS
					agentready = true ;
					agentbusy = false ;
					
					$('#agentstatus').addClass("layui-form-onswitch");
					$('#agentstatus_busy').removeClass("layui-form-onswitch-busy").show();
				}
			}).on('task', function(data) {
				
		    }).on('trans', function(data) {
		    	var index = layer.open({
		    		  type: 1
		    		  ,title:data.title
		    		  ,offset: 'auto' //具体配置参考：offset参数项
		    		  ,content: "<div style='padding:5px 20px;'>"+data.memo+"</div>"
		    		  ,btn: ['同意','拒接']
		    		  ,time:transtimeout
		    		  ,btnAlign: 'c' //按钮居中
		    		  ,shade: 0 //不显示遮罩
		    		  ,yes: function(){
		    			  layer.close(index);
		    		     loadURL('/agent/transfer/accept.html?userid='+data.userid);
		    		  }
		    		  ,btn2: function(){
		    			  layer.close(index);
		    		     loadURL('/agent/transfer/refuse.html?userid='+data.userid);
		    		  }
		    		  ,cancel: function(){
		    			  layer.close(index);
		    		     loadURL('/agent/transfer/refuse.html?userid='+data.userid);
		    		  }
		    		});
		    }).on('new', function(data) {
		    	if($('#multiMediaDialogWin').length > 0 && multiMediaDialogWin.$ &&multiMediaDialogWin.$('#agentusers').length > 0){
		    		multiMediaDialogWin.Proxy.newAgentUserService(data);
		    	}else{
		    		//来电弹屏
		    		$('#agentdesktop').attr('data-href' , '/agent/index.html?userid='+data.userid).click();
		    	}
		    	WebIM.audioplayer('audioplane', newuser, false); // 播放
		    }).on('exchange', function(data) {
		    	if($('#multiMediaDialogWin').length > 0 && multiMediaDialogWin.$ &&multiMediaDialogWin.$('#agentusers').length > 0){
		    		multiMediaDialogWin.Proxy.exchangeAgentUserService(data);
		    	}else{
		    		//来电弹屏
		    		$('#agentdesktop').attr('data-href' , '/agent/index.html?userid='+data.userid).click();
		    	}
		    }).on('status', function(data) {
		    	if(orgi == data.orgi){
		    		$('#agents_status').html("服务人数："+data.users+"人，排队数："+data.inquene+"人，在线坐席："+data.agents+"人，坐席忙："+data.busy+"人");	        	
		    	}
		    }).on('message', function(data) {
		    	if($('#multiMediaDialogWin').length > 0 && multiMediaDialogWin != null && multiMediaDialogWin.$ && multiMediaDialogWin.$('#agentusers').length > 0){
		    		multiMediaDialogWin.Proxy.newAgentUserMessage(data);
		    		if(data.type == 'message'){
		    			if(tipagent && tipagent == 'true'){
		    				WebIM.showNotice(tipagenttitle , data.puremsg , tipagenticon);
		    			}
		        		WebIM.audioplayer('audioplane', newmessage, false); // 播放
		        	}
		    	}else{
		    		//来电弹屏
		    		$('#agentdesktop').attr('data-href' , '/agent/index.html?userid='+data.userid).click();
		    	}
		    }).on('workorder', function(data) {
		        
		    }).on('end', function(data) {
		    	if($('#multiMediaDialogWin').length > 0){
		    		if(multiMediaDialogWin.document.getElementById('agentusers') != null){
		    			multiMediaDialogWin.Proxy.endAgentUserService(data);
		    		}
		    	}else{
		    		//来电弹屏
		    		$('#agentdesktop').attr('data-href', '/agent/index.html?userid='+data.userid).click();
		    	}
		    });	
		},
		off:function(){
			webIMAgent.delevent('connect');
			webIMAgent.delevent('disconnect');
			webIMAgent.delevent('agentstatus');
			webIMAgent.delevent('chatevent');
			webIMAgent.delevent('workstatus');
			webIMAgent.delevent('trans');
			webIMAgent.delevent('trans');
			webIMAgent.delevent('new');
			webIMAgent.delevent('exchange');
			webIMAgent.delevent('message');
			webIMAgent.delevent('status');
			webIMAgent.delevent('workorder');
			webIMAgent.delevent('end');
			
			
		},
		delevent:function(name){
			var event = socket.listeners(name) ;
			if(event.length > 1){
				for(i = 0 ; i<event.length ; i++){
    				socket.off(name , event[i]);
				}
			}else{
				socket.off(name , event[0]);
			}
		}
}

$(document).ready(function(){
	webIMAgent.init();
	/****每分钟执行一次，与服务器交互，保持会话****/
	setInterval(function(){
		WebIM.ping();	
	} , 30000);				
}) ;

var WebIM = {
	sendMessage:function(message , userid , appid , session , orgi , touser , agentstatus){
		WebIM.sendTypeMessage(message, userid, appid, session, orgi, touser, agentstatus, null , null) ;
	},
	sendTypeMessage:function(message , userid , appid , session , orgi , touser , agentstatus , msgtype , attachmentid){
		socket.emit('message', {
			appid : appid ,
			userid:userid,
			sign:session,
			touser:touser,
			session: session ,
			orgi:orgi,
			username:agentstatus,
			nickname:agentstatus,
			message : message,
			msgtype:msgtype,
			attachmentid:attachmentid
        });
	},
	showNotice:function (title , content , icon) {   
	    Notification.requestPermission(function (perm) {  
	        if (perm == "granted") {  
	            var notification = new Notification(title, {  
	                dir: "auto",  
	                lang: "zh",  
	                tag: "UCKeFu", 
	                icon:icon,
	                body: content
	            });  
	            setTimeout(function(){
	            	notification.close();
	            },5000);    
	        }  
	    });  
	}, 
	ping : function(){
		loadURL("/message/ping.html",null,function(data){
			if(data!=''  && data.indexOf('login') >=0){
				window.location.href = "/login.html" ;
			}
		}) ;	
	},
	audioplayer:function(id, file, loop) {
	    var audioplayer = document.getElementById(id);
	    if (audioplayer != null) {
	        document.body.removeChild(audioplayer);
	    }

	    if (typeof(file) != 'undefined') {
	        if (navigator.userAgent.indexOf("MSIE") > 0) { // IE 
	            var player = document.createElement('bgsound');
	            player.id = id;
	            player.src = file['mp3'];
	            player.setAttribute('autostart', 'true');
	            if (loop) {
	                player.setAttribute('loop', 'infinite');
	            }
	            document.body.appendChild(player);

	        } else { // Other FF Chome Safari Opera 
	            var player = document.createElement('audio');
	            player.id = id;
	            player.setAttribute('autoplay', 'autoplay');
	            if (loop) {
	                player.setAttribute('loop', 'loop');
	            }
	            document.body.appendChild(player);

	            var mp3 = document.createElement('source');
	            mp3.src = file['mp3'];
	            mp3.type = 'audio/mpeg';
	            player.appendChild(mp3);
	        }
	    }
	},
	audiostop:function(id){
		var player = document.getElementById(id);
		if(player!=null){
			player.pause();
			player.currentTime = 0;
			if($('#'+id).length > 0){
				$('#'+id).remove();
			}
		}
	}
}


